package net.pm.core.filter;

import java.io.IOException;
import java.net.URL;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.pm.common.toolkit.DevConstant;
import net.pm.common.toolkit.PMTool;
import net.pm.common.toolkit.date.DateUtils;
import net.pm.core.cache.SessionStorer;

import org.apache.commons.lang3.ArrayUtils;


/**
 * 全局过滤器(包括静态资源)
 *
 */
@WebFilter(description = "GlobalRequestFilter", urlPatterns = {"*"})
public class GlobalRequestFilter implements Filter {
	
	//不检查session的URL
	private static final String[] UNCHECKSESSION_URLS = 
		{"/login.htm","/register.htm","/error/kaptcha.htm"};

    public GlobalRequestFilter() {}

    
	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		
	
		
		final HttpServletRequest request = (HttpServletRequest)req;
		final HttpServletResponse response = (HttpServletResponse)res;
		//自定义server字段
		response.setHeader("Server", "PMWS/1.0");
		
		final HttpSession session = request.getSession();
		final String requesturi = request.getRequestURI();
		
		session.setAttribute(DevConstant.SESSION_LAST_REQUEST_TIME,DateUtils.obtainCurrentStrdate());
		
		
		if(DevConstant.BASEPATH == null)
			DevConstant.BASEPATH = request.getContextPath();

		{
			req.setCharacterEncoding("UTF-8");		//设置请求编码为(utf-8)
			res.setCharacterEncoding("UTF-8");		//设置响应编码为(utf-8)
		}
		

	
		
		//检查Referer,防止CSRF攻击
		{
			final String requestreferer = request.getHeader("Referer");
			if(requestreferer != null){	// && !request.getRequestURI().endsWith(DENY_IMAGE_NAME)
				final URL refererurl = new URL(requestreferer);
				final String refererhost = refererurl.getHost();
				final int refererport = refererurl.getPort();	//如果不填，为-1
				final String myhost = request.getServerName();
				final int myport = request.getLocalPort();
				
				if(!refererhost.equals(myhost))
					return;
				
				if(refererport == -1){
					if(myport != 80 && myport != 443)
						return;
				}else{
					if(refererport != myport)
						return;
				}
				
			}
		}
		
		
		//判断次url是否需要进行session检查
		boolean needchecksession = true;
		if ((!requesturi.endsWith(".htm"))
				|| ArrayUtils.contains(UNCHECKSESSION_URLS,
						requesturi.substring(DevConstant.BASEPATH.length())))
			needchecksession = false;

		if(needchecksession){
			if (session.getAttribute(DevConstant.SESSION_CURRENT_USER) == null) {

				session.setAttribute(DevConstant.SHOW_MESSAGESS, "尚未登录或会话过期.");
				response.sendRedirect(DevConstant.BASEPATH + "/login.htm");
				return;
			}
			//帐号在别处登录,或被管理员禁用时
			if (SessionStorer.fetchBySessionId(session.getId()) == null) {
				PMTool.clearSession(session);
				session.setAttribute(DevConstant.SHOW_MESSAGESS, "此帐号已在别处登录.");
				response.sendRedirect(DevConstant.BASEPATH+"/login.htm");
				return;
			}
			
		}
		
		chain.doFilter(req, res);
		return;
	}
	

	
	@Override
	public void destroy() {}
	
	@Override
	public void init(FilterConfig fConfig) throws ServletException {}

}
